<?php
if (!defined('BASEPATH'))
    exit('No direct script access allowed');


/**
 * Initialize Messages that will be shown on the user screen.
 * @access public 
 */
function init_user( $role )
{
    $ci = &get_instance();
    $cms_config = $ci->cms;
    
    // initialize user messages
    init_messages('User');
    
    $ci->options_markup = '';
    $ci->options_markup .= '<a href="' . base_url() . 'users/' . $role['plural'] . '/preview/id/$1" class="btn btn-info btn-xs with-modal btn-preview" rel="tooltip" title="Preview Record"><i class="fa fa-search"></i></a>' . "\n";
    $ci->options_markup .= '<a href="' . base_url() . 'users/' . $role['plural'] . '/edit/id/$1" class="btn btn-primary btn-xs with-modal btn-edit" rel="tooltip" title="Edit Record"><i class="fa fa-pencil"></i></a>' . "\n";
    $ci->options_markup .= '<a href="' . base_url() . 'users/' . $role['plural'] . '/delete/id/$1" class="btn btn-danger btn-xs with-modal btn-delete"rel="tooltip" title="Delete Record"><i class="fa fa-trash-o"></i></a>';

    // @TODO magforeach ka dito
    // initialize table query table columns
    $ci->alias  = '';
    $ci->alias .= $cms_config['db_prefix'] . $role['plural'] . '.id AS id,';
    $ci->alias .= $cms_config['db_prefix'] . $role['plural'] . '.first_name AS first_name,';
    $ci->alias .= $cms_config['db_prefix'] . $role['plural'] . '.last_name AS last_name,';
    $ci->alias .= $cms_config['db_prefix'] . $role['plural'] . '.speciality AS speciality,';
    $ci->alias .= $cms_config['db_prefix'] . $role['plural'] . '.date_created AS date_created,';
    $ci->alias .= $cms_config['db_prefix'] . $role['plural'] . '.date_modified AS date_modified,';
    $ci->alias .= $cms_config['db_prefix'] . $role['plural'] . '.status AS status ';
    
//    // initialize search columns
//    $search_columns = array();
//    array_push( $search_columns, $cms_config['db_prefix'] . 'name' );
//    array_push( $search_columns, $cms_config['db_prefix'] . 'description' );
//    array_push( $search_columns, $cms_config['db_prefix'] . 'status' );
//    $ci->search_columns = $search_columns;

//    // initialize table headers
//    $table_headers = array();
//    $table_headers['name'] = 'Name';
//    $table_headers['description'] = 'Description';
//    $table_headers['date_created'] = 'Date Created';
//    $table_headers['date_modified'] = 'Date Modified';
//    $table_headers['status'] = 'Status';
//    $ci->table_headers = create_datatable_headers($table_headers, 'users', 2);

    // initialize customized table columns
    $ci->custom_columns = array();
    
    $date_created = array();
    $date_created['keys'] = 'cms_date(date_created)';
    $date_created['markup'] = '$1';
    $ci->custom_columns['date_created'] = $date_created;
    
    $date_modified = array();
    $date_modified['keys'] = 'cms_date(date_modified)';
    $date_modified['markup'] = '$1';
    $ci->custom_columns['date_modified'] = $date_modified;
    
//    $status['keys'] = 'cms_status_toggle(status, users/confirm_update/, id)';
//    $status['markup'] = '$1';
//    $ci->custom_columns['status'] = $status;
    
}

/*
 * Method for validating posted values.
 * @access public
 * @retrun bool Returns true if the validation was successful, otherwise sends invalid response.
 */
function valid_add_user()
{
    $ci = &get_instance();
    $cms = $ci->cms;

    $ci->form_validation
            ->set_rules('first-name',       'first name',       'trim|required|max_length[25]|xss_clean')
            ->set_rules('last-name',        'last name',        'trim|required|max_length[25]|xss_clean')
            ->set_rules('username',         'username',         'trim|required|max_length[25]|xss_clean')
            ->set_rules('email',            'email',            'trim|required|valid_email|max_length[100]|xss_clean')
            ->set_rules('password',         'password',         'trim|required|max_length[25]|xss_clean')
            ->set_rules('confirm-password', 'confirm password', 'trim|required|matches[password]|max_length[25]|xss_clean')
            ->set_rules('status',       'status',       'trim|max_length[10]|xss_clean');
            
    return $ci->form_validation->run();
}

/*
 * Method for validating posted values.
 * @access public
 * @retrun bool Returns true if the validation was successful, otherwise sends invalid response.
 */
function valid_edit_user()
{
    $ci = &get_instance();
    $ci->form_validation->set_rules('id', 'ID', 'trim|required|numeric|max_length[10]|xss_clean');
    
    $ci->input->post('first-name')          ? $ci->form_validation->set_rules('first-name',         'first name',       'trim|required|max_length[25]|xss_clean')           : '';
    $ci->input->post('last-name')           ? $ci->form_validation->set_rules('last-name',          'last name',        'trim|required|max_length[25]|xss_clean')           : '';
    $ci->input->post('username')            ? $ci->form_validation->set_rules('username',           'username',         'trim|required|max_length[25]|xss_clean')           : '';
    $ci->input->post('email')               ? $ci->form_validation->set_rules('email',              'email',            'trim|required|valid_email|max_length[100]|xss_clean')         : '';
    $ci->input->post('password')            ? $ci->form_validation->set_rules('password',           'password',         'trim|required|max_length[25]|xss_clean')         : '';
    $ci->input->post('confirm-password')    ? $ci->form_validation->set_rules('confirm-password',   'confirm password', 'trim|required|matches[password]|max_length[25]|xss_clean')         : '';
    $ci->input->post('status')              ? $ci->form_validation->set_rules('status',             'status',           'trim|max_length[10]|xss_clean')                    : '';
    
    return $ci->form_validation->run();
}

/*
 * Method for validating posted values.
 * @access public
 * @retrun bool Returns true if the validation was successful, otherwise sends invalid response.
 */
function valid_delete_user()
{
    $ci = &get_instance();
    $ci->form_validation->set_rules('id', 'ID', 'trim|required|numeric|max_length[10]|xss_clean');
    return $ci->form_validation->run();
}

/**
 * Add user to database
 * @return array
 */
function add_user()
{
    $ci = &get_instance();
    
    $user = array();
    set_value('name')           ? $user['name']           = clean_text( set_value('name') )               : '';
    set_value('description')    ? $user['description']    = clean_text( set_value('description') )        : '';
    set_value('status')         ? $user['status']         = clean_text( set_value('status') )             : 'active';

    $user_id = $ci->user_model->insert($user);
    $user['id'] = $user_id;
    return $user;
}

/**
 * Edit user
 * @param int $id
 * @return array
 */
function edit_user( $id = NULL )
{
    $ci = &get_instance();
    
    $user = array();
    set_value('id')             ? $user['id']             = clean_text( set_value('id') )                 : '';
    set_value('name')           ? $user['name']           = clean_text( set_value('name') )               : '';
    set_value('description')    ? $user['description']    = clean_text( set_value('description') )        : '';
    set_value('status')         ? $user['status']         = clean_text( set_value('status') )             : '';
    $user['date_modified'] = date('Y-n-d H:i:s');

    $user_id           = isset( $user['id'] ) ? $user['id'] : $id;
    $edited_rows        = $ci->user_model->find_update( $user_id, $user );
    $response_user     = $edited_rows >= 0  ? $ci->user_model->find($user_id)->get() : NULL;
    return $response_user;
}

function delete_user( $id = NULL )
{
    $ci = &get_instance();
    
    $user = array();
    $ci->input->post('id') ? $user['id'] = set_value('id') : '';
    
    $user_id = isset( $user['id'] ) ? $user['id'] : $id;
    $deleted = $ci->user_model->find_delete( $user_id );
    return $deleted;
}

/**
 * Displays users list page.
 * @access public
 * @param array $content An array of users to be shown.
 * @param string $message The type of message to be shown.
 */
function view_users_list($content = NULL, $message_type = NULL)
{
    $ci = &get_instance();

    $data = array();
    
    // set message
    $message                    = get_message($message_type);
    $data['message']            = $message;
    
    if($content === NULL)
    {
        $data['users'] = $ci->user_model->all()->get();
    } else
    {
        $data['users'] = $content;
    }
    
//    echo '<pre>';
//    print_r($data['users']); 
//    echo '</pre>';
//    exit();
    

    // active navigation
    $data['navigation'] = 'users';
    
    // create breadcrumbs
    clear_breadcrumbs();
    store_breadcrumbs('Users', 'users');
    build_breadcrumbs();

    // build template
    $ci->template
            ->title('Users')
            ->set_layout('main')
            ->set_partial('navigation', 'layouts/navigation')
            
            ->set_partial('users', 'user_table')
            
            ->set_partial('footer', 'layouts/footer')
            ->set_partial('notifications', 'layouts/notifications')
            ->set_partial('modal', 'layouts/modal')
            ->build('user_list', $data);
}

/**
 * Displays user info.
 * @access public
 * @param int $user_id ID of the record to be shown.
 */
function view_user_preview($user_id)
{
    $ci = &get_instance();

    // company info
    $data = array();
    $data['user_infos'] = $ci->user_model->find($user_id)->get();

    // active navigation
    $data['navigation'] = 'users';

    // create breadcrumbs
    store_breadcrumbs('Preview User', 'users/preview/id/' . $user_id);
    build_breadcrumbs();
    
    // build template
    $ci->template
            ->title('User')
            ->set_layout('main')
            ->set_partial('navigation', 'layouts/navigation')
            ->set_partial('footer', 'layouts/footer')
//            ->set_partial('notifications', 'layouts/notifications')
//            ->set_partial('modal', 'layouts/modal')
            ->build('user_preview', $data);
}

/**
 * Displays the form for adding or editing users.
 * @access public
 * @param string $title String representing the title page.
 * @param string $crumb The string that will be appended to the end of the breadcrumb.
 * @param string $message The type of message that will be shown on the form. Default value is null.
 * @param array $record An array containing record info to be edited. Default value is null.
 */
function view_user_form($title, $message_type = NULL, $record = NULL)
{
    $ci = &get_instance();
    $data = array();
    
    // set message
    $message                    = get_message($message_type);
    $data['message']            = $message;

    // set form data
    $data['action'] = $title == 'Add User' ? 'add' : 'edit';
    $data['add'] = $title == 'Add User' ? TRUE : FALSE;
    $data['add_another'] = $ci->input->post('add-another') ? ' checked="checked"' : '';

    // set user data
    $data['id'] = isset($record['id']) ? $record['id'] : set_value('id');
    
    $data['photo']              = isset($record['photo']) ? $record['photo'] : set_value('photo');
    $data['photo_image']        = ( $title == 'Add User' || ! $data['photo'] ) ? base_url() . 'resources/images/no_image.gif' : base_url() . $ci->photo_path . $data['photo'];

    $data['first_name']         = isset($record['first_name']) ? $record['first_name'] : set_value('first-name');
    $data['first-name-status']  = form_error('first-name') ? ' has-error' : '';
    
    $data['last_name']          = isset($record['last_name']) ? $record['last_name'] : set_value('first-name');
    $data['last-name-status']   = form_error('last-name') ? ' has-error' : '';
    
    $data['username']           = isset($record['username']) ? $record['username'] : set_value('username');
    $data['username-status']    = form_error('username') ? ' has-error' : '';
    
    $data['email']              = isset($record['email']) ? $record['email'] : set_value('email');
    $data['email-status']       = form_error('email') ? ' has-error' : '';
    
    $data['password-status']            = form_error('password') ? ' has-error' : '';
    $data['confirm-password-status']    = form_error('confirm-password') ? ' has-error' : '';
    
    $data['status']             = isset($record['status']) ? $record['status'] : set_value('status');
    
    // set active navigation
    $data['navigation'] = 'users';
    
    // create breadcrumbs
    clear_breadcrumbs();
    store_breadcrumbs('Add Users', 'users/add');
    build_breadcrumbs();

    // build template
    $ci->template
            ->title($title)
            ->set_layout('main')
            ->set_partial('navigation', 'layouts/navigation')
            ->set_partial('footer', 'layouts/footer')
            ->set_partial('notifications', 'layouts/notifications')
//            ->set_partial('modal', 'layouts/modal')
            ->build('user_form', $data);
    
}

/**
 * Formats an array of records to valid response.
 * @access public
 * @param array $users Array of users
 */
function response_users($users)
{
    $ci = &get_instance();
    
    $params = $ci->input->post();
    $case = isset( $params['case'] ) ? $params['case'] : 'snake';
    
    $response_users = array();
    foreach($users as $user)
    {
        $response_user                   = array();
        isset($user['id'])               ? $response_user[changeCase('id', $case)]               = clean( $user['id'] ) : '';
        isset($user['name'])             ? $response_user[changeCase('name', $case)]             = clean( $user['name'] ) : '';
        isset($user['description'])      ? $response_user[changeCase('description', $case)]      = clean( $user['description'] ) : '';
        isset($user['date_created'])     ? $response_user[changeCase('date_created', $case)]     = clean( $user['date_created'] ) : '';
        isset($user['date_modified'])    ? $response_user[changeCase('date_modified', $case)]    = clean( $user['date_modified'] ) : '';
        isset($user['status'])           ? $response_user[changeCase('status', $case)]           = clean( $user['status'] ) : '';

        array_push($response_users, $response_user);
    }
    
    // we format our response
    if( count($response_users) > 0 ) // check if not empty
    {
        format_response('success', 200, 'Response Users.', NULL, $response_users);
    }
    else
    {
        format_response('success', 200, 'No Data Available', NULL, 'No Data Available');
    }
    
}

/* End of file user_helper.php */
/* Location: ./application/users/backend-users/helpers/user_helper.php */